package com.lz.config.common.security.controller;

import com.google.gson.Gson;
import com.lz.common.anno.CommonSum;
import com.lz.common.baseBean.R;
import com.lz.config.common.security.domain.MyUserDetails;
import com.lz.config.common.utils.JwtUtil;
import com.lz.config.dal.entity.User;
import com.lz.config.dal.mapper.UserMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RequestMapping("/api/user")
@RestController
@CommonSum
public class UserController {

    @Resource
    private UserMapper userMapper;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private Gson gson;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 注册
     */

    @RequestMapping("/add")
    public R add(String username, String password) {
        String encode = passwordEncoder.encode(password);
        try {
            userMapper.insert(new User(null, username, 0, null, encode));
        } catch (Exception e) {
            return R.error("用户已存在");
        }
        return R.success();
    }

    /**
     * 登录
     */
    @RequestMapping("/login")
    public R login(String username, String password) {
        Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        if (authenticate == null) {
            throw new RuntimeException("用户名为空");
        }
        MyUserDetails userDetails = (MyUserDetails) authenticate.getPrincipal();
        String id = userDetails.getUser().getId();
        String json = gson.toJson(userDetails);

        redisTemplate.opsForValue().set("login:" + id, json, 30 * 60, java.util.concurrent.TimeUnit.SECONDS);
        MyUserDetails a = gson.fromJson(json, MyUserDetails.class);
        System.out.println(a);
        String usernameFromToken = JwtUtil.createToken(id);
        return R.success(usernameFromToken);
    }


}
